﻿/*最后修改 2013/8/30 11:27
 * */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.Text;
using System.IO;
using System.Data.SqlClient;
using System.Configuration;

public partial class menu_create : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["USERNAME"] == null)
        {
            Response.Redirect("error_log.aspx", true);
        }
        if (Session["IDENTITY"].Equals("employee") == true)
        {
            Response.Redirect("error_auth.aspx", true);
        }
    }
   
    
    /// <summary>
    /// 提交创建请求
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void button2_Click(object sender, EventArgs e)
    {
        string str;
        string appid = textbox1.Text;
        string appsecret = textbox2.Text;
        string token = "";
        if (appid != null && appsecret != null && appid != "" && appsecret != "")
            str = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + appsecret;
        else
        {
            Page.RegisterStartupScript("ss", "<script>alert('APPID和APPSECRET不能为空！')</script>");
            return;
        }
        try
        {
            string result = GetModel(str);
            if (result.Substring(2, 12).Equals("access_token") == true)
            {
                 token=result.Substring(17, 150);
            }
            else if (result.Substring(2, 7).Equals("errcode") == true)
            {
                Page.RegisterStartupScript("ss", "<script>alert('出错啦，请重试！" + result + "')</script>");
                return;
            }
            else
            {
                Page.RegisterStartupScript("ss", "<script>alert('未知错误，请重试！')</script>");
                return;
            }
        }
        catch (Exception ee)
        {
            Page.RegisterStartupScript("ss", "<script>alert('出错啦，请重试！" + ee.Message + ee.StackTrace + "')</script>");
            return;
        }


        SqlConnection sc1 = new SqlConnection(ConfigurationManager.ConnectionStrings["wbkpt"].ConnectionString.ToString());
        sc1.Open();
        SqlCommand get_sum = new SqlCommand("select count(SORT_NAME) from INFO_SORT where SORT_LEVEL=@l and ENTER_ID=@eid1", sc1);
        get_sum.Parameters.AddWithValue("@l", "主要产品");
        get_sum.Parameters.AddWithValue("@eid1",Session["ENTERID"].ToString());
        int count_sort = Convert.ToInt32(get_sum.ExecuteScalar().ToString());
        if (count_sort > 4)
        {
            sc1.Close();
            Page.RegisterStartupScript("ss", "<script>alert('数据库出现错误！')</script>");
            return;
        }
        else
        {
            #region 生成自定义菜单JSON
            string weixin1 = "";
            weixin1 += "{\n";
            weixin1 += "\"button\":[\n";
            weixin1 += "{\n";
            weixin1 += "\"name\":\"活动精选\",\n";
            weixin1 += "\"sub_button\":[\n";
            weixin1 += "{\n";
            weixin1 += "\"type\":\"click\",\n";
            weixin1 += "\"name\":\"本期优惠\",\n";
            weixin1 += "\"key\":\"DISC_INFO\"\n";
            weixin1 += "},\n";
            weixin1 += "{\n";
            weixin1 += "\"type\":\"click\",\n";
            weixin1 += "\"name\":\"本期抽奖\",\n";
            weixin1 += "\"key\":\"LOTTERY_INFO\"\n";
            weixin1 += "},\n";
            weixin1 += "{\n";
            weixin1 += "\"type\":\"click\",\n";
            weixin1 += "\"name\":\"产品精选\",\n";
            weixin1 += "\"key\":\"SPECIAL_INFO\"\n";
            weixin1 += "}]\n";
            weixin1 += "},\n";

            //第二菜单栏，先获取主要产品分类数量，若等于4则最后一个按钮显示查看更多，若小于4则直接添加主要分类按钮，最后一个按钮设置为查看更多
            weixin1 += "{\n";
            weixin1 += "\"name\":\"产品介绍\",\n";
            weixin1 += "\"sub_button\":[\n";
            #region 第二菜单栏处理
            //获取以下用户ID
          
            string user_id = Session["ENTERID"].ToString();

            string[] sort_name = new string[5]{null,null,null,null,null};
            SqlCommand get_sort1 = new SqlCommand();
            get_sort1.Connection = sc1;
            get_sort1.CommandText = "select SORT_NAME from INFO_SORT where SORT_LEVEL=@ll and ENTER_ID=@eid2";
            get_sort1.Parameters.AddWithValue("@ll", "主要产品");
            get_sort1.Parameters.AddWithValue("@eid2", Session["ENTERID"].ToString());
            SqlDataReader re = get_sort1.ExecuteReader();
            int i = 0;
            if (re != null)
            {
                while (re.Read())
                {
                    sort_name[i] = re.GetString(re.GetOrdinal("SORT_NAME"));
                    i++;
                }
            }
            int k = 0;
            while(sort_name[k]!=null)
            {
                weixin1 += "{\n";
                weixin1 += "\"type\":\"view\",\n";
                weixin1 += "\"name\":\""+sort_name[k]+"\",\n";
                weixin1 += "\"url\":\"http://lcsy2008.eicp.net/wbkpro/mobile_sortsearch.aspx?eid="+user_id+"&sname="+sort_name[k]+"\"\n";
                weixin1 += "},\n";
                k++;
            }
            #endregion
            weixin1 += "{\n";
            weixin1 += "\"type\":\"view\",\n";
            weixin1 += "\"name\":\"查看更多...\",\n";
            weixin1 += "\"url\":\"http://lcsy2008.eicp.net/wbkpro/mobile_moresort.aspx?eid=" + user_id + "\"\n";
            weixin1 += "}]\n";
            weixin1 += "},\n";    
            weixin1 += "{\n";
            weixin1 += "\"name\":\"平台服务\",\n";
            weixin1 += "\"sub_button\":[\n";
            weixin1 += "{\n";
            weixin1 += "\"type\":\"click\",\n";
            weixin1 += "\"name\":\"会员特权\",\n";
            weixin1 += "\"key\":\"USER_INFO\"\n";
            weixin1 += "},\n";
            weixin1 += "{\n";
            weixin1 += "\"type\":\"click\",\n";
            weixin1 += "\"name\":\"我要换购\",\n";
            weixin1 += "\"key\":\"HG_INFO\"\n";
            weixin1 += "},\n";
            weixin1 += "{\n";
            weixin1 += "\"type\":\"click\",\n";
            weixin1 += "\"name\":\"联系我们\",\n";
            weixin1 += "\"key\":\"CONTACT_INFO\"\n";
            weixin1 += "}]\n";
            weixin1 += "}]\n";
            weixin1 += "}\n";
            #endregion
            string tmpi = GetPage("https://api.weixin.qq.com/cgi-bin/menu/create?access_token="+token, weixin1);
            if (tmpi.Substring(11, 1) == "0")
            {//成功
                sc1.Close();
                Page.RegisterStartupScript("ss", "<script>alert('成功提交，请在24小时内查看微信公众平台或重新关注查看效果！')</script>");
                return;
            }
            else
            {
                sc1.Close();
                Page.RegisterStartupScript("ss", "<script>alert('请求提交出错，请核对凭证后重新尝试！')</script>");
                return;
            }
        }
    }
    /// <summary>
    /// GET获取微信凭证接口
    /// </summary>
    /// <param name="strUrl"></param>
    /// <returns></returns>
    private string GetModel(string strUrl)
    {

        string strRet = null;
        try
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strUrl);
            request.Timeout = 2000;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            System.IO.Stream resStream = response.GetResponseStream();
            Encoding encode = System.Text.Encoding.Default;
            StreamReader readStream = new StreamReader(resStream, encode);
            Char[] read = new Char[256];
            int count = readStream.Read(read, 0, 256);
            while (count > 0)
            {
                String str = new String(read, 0, count);
                strRet = strRet + str;
                count = readStream.Read(read, 0, 256);
            }
            resStream.Close();
        }
        catch (Exception e)
        {
            strRet = "";
        }
        return strRet;
    }
    

    /// <summary>
    /// POST提交自定义菜单创建请求
    /// </summary>
    /// <param name="posturl"></param>
    /// <param name="postData"></param>
    /// <returns></returns>
    public string GetPage(string posturl, string postData)
    {
        Stream outstream = null;
        Stream instream = null;
        StreamReader sr = null;
        HttpWebResponse response = null;
        HttpWebRequest request = null;
        Encoding encoding = Encoding.UTF8;
        byte[] data = encoding.GetBytes(postData);
        // 准备请求...
        try
        {
            // 设置参数
            request = WebRequest.Create(posturl) as HttpWebRequest;
            CookieContainer cookieContainer = new CookieContainer();
            request.CookieContainer = cookieContainer;
            request.AllowAutoRedirect = true;
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = data.Length;
            outstream = request.GetRequestStream();
            outstream.Write(data, 0, data.Length);
            outstream.Close();
            //发送请求并获取相应回应数据
            response = request.GetResponse() as HttpWebResponse;
            //直到request.GetResponse()程序才开始向目标网页发送Post请求
            instream = response.GetResponseStream();
            sr = new StreamReader(instream, encoding);
            //返回结果网页（html）代码
            string content = sr.ReadToEnd();
            string err = string.Empty;
            return content;
        }
        catch (Exception ex)
        {
            string err = ex.Message;
            return string.Empty;
        }
    }
}